package license

import (
	"context"
	"encoding/json"
	"strings"

	v1 "gitee.com/liangziyisheng/caas-platform-mc/api/license/v1"
	"gitee.com/liangziyisheng/caas-platform-mc/internal/consts"
	"gitee.com/liangziyisheng/caas-platform-mc/internal/model/entity"
	"gitee.com/liangziyisheng/caas-platform-mc/internal/service"
	"gitee.com/liangziyisheng/caas-platform-mc/utility/cache"
	"gitee.com/liangziyisheng/caas-platform-mc/utility/utils"

	"github.com/gogf/gf/v2/errors/gerror"
)

func (c *ControllerV1) List(ctx context.Context, req *v1.ListReq) (res *v1.ListRes, err error) {
	// tenantCode := ctx.Value(consts.TokenClaims.TenantCode).(string)
	in := &v1.ListInput{}
	utils.CopyStruc(*req, in)
	out, err := service.License().List(ctx, in)
	if err != nil {
		return nil, err
	}
	res = &v1.ListRes{Total: out.Total, Data: make([]v1.LicRes, 0)}

	if out.Total > 0 {
		// 获取应用名称
		cc, _ := cache.NewCache()
		cache.InitCache(ctx, consts.InitialCacheKeys.AppsKey, false)
		val, err := cc.Get(ctx, consts.InitialCacheKeys.AppsKey)
		if err != nil {
			return nil, gerror.WrapCode(consts.GetCacheFailed, err)
		}
		cKey, ok := val.Val().(string)
		if !ok {
			return nil, gerror.WrapCode(consts.ParseCacheFailed, gerror.New("applications缓存解析出错"))
		}
		appMap := make(map[string]entity.App, 0)
		json.Unmarshal([]byte(cKey), &appMap)

		// 获取租户名称
		cache.InitCache(ctx, consts.InitialCacheKeys.TenantsKey, false)
		val, err = cc.Get(ctx, consts.InitialCacheKeys.TenantsKey)
		if err != nil {
			return nil, gerror.WrapCode(consts.GetCacheFailed, err)
		}
		cKey, ok = val.Val().(string)
		if !ok {
			return nil, gerror.WrapCode(consts.ParseCacheFailed, gerror.New("tenant缓存解析出错"))
		}
		tenantMap := make(map[string]entity.Tenant, 0)
		json.Unmarshal([]byte(cKey), &tenantMap)

		for _, v := range out.Data {
			if req.TenantName != "" && !strings.Contains(tenantMap[v.TenantCode].Name, req.TenantName) {
				continue
			}
			if req.AppName != "" && appMap[v.AppCode].Name != req.AppName {
				continue
			}
			l := v1.LicRes{
				Id:         v.Id,
				TenantCode: v.TenantCode,
				TenantName: tenantMap[v.TenantCode].Name,
				AppCode:    v.AppCode,
				UserLimit:  v.UserLimit,
				AppName:    appMap[v.AppCode].Name,
				AppDesc:    appMap[v.AppCode].Description,
				ExpiredAt:  v.ExpiredAt,
				Status:     v.Status,
			}
			res.Data = append(res.Data, l)

		}
	}
	return res, nil
}
